package com.skymxc.skin

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.AssetManager
import android.content.res.Resources
import android.text.TextUtils
import android.util.Log
import java.util.*

/**
 * <p>
 * 皮肤管理
 * </p>
 *
 * @author 孟祥超
 * <p>
 * date: 2021/9/20  9:36 下午
 */
object SkinManager : Observable() {

    private lateinit var mContext:Context
    fun init(application: Application){
        mContext = application
        /**
         * 1.偏好设置，记录当期使用的皮肤
         * 2.资源管理器，用于加载皮肤包
         * 3.注册 Activity 生命周期，设置被观察者
         * 4.加载上次使用的皮肤
         */
        SkinPreferences.init(application)
        SkinResources.init(application)
        application.registerActivityLifecycleCallbacks(ActivityLifecycle(this))
        loadSkin(SkinPreferences.getInstance().getSkin())
    }

    @SuppressLint("StaticFieldLeak")
    fun loadSkin(path:String?){
        Log.i("SkinManager", "loadSkin: path->$path")
        if (TextUtils.isEmpty(path)){
            //还原默认皮肤
            SkinResources.getInstance().reset()
            SkinPreferences.getInstance().reset()
        }else{
            /**
             * 1.反射创建 AssetManager，Resource
             *  a.
             */
            // 反射创建 AssetManager，Resource
            val assetManagerClass =AssetManager::class.java
            val assetManager = assetManagerClass.newInstance()
            //资源路径设置目录 通过反射调用  addAssetPath 方法
            val declaredMethod =
                assetManagerClass.getDeclaredMethod("addAssetPath", String::class.java)

            declaredMethod.invoke(assetManager,path)

            //宿主app的 resources;
           val appResource = mContext.resources

            //根据当前的设备显示器信息 与 配置(横竖屏、语言等) 创建Resources
            val skinResource = Resources(assetManager,appResource.displayMetrics,appResource.configuration)


            //获取外部Apk(皮肤包) 包名
            val packageManager = mContext.packageManager

            val packageInfo = packageManager.getPackageArchiveInfo(path!!,PackageManager.GET_ACTIVITIES)
            if (null==packageInfo){
                //还原默认皮肤
                SkinResources.getInstance().reset()
                SkinPreferences.getInstance().reset()
            }else {
                val packageName = packageInfo.packageName
                SkinResources.getInstance().applySkin(skinResource,packageName)
                //记录路径
                SkinPreferences.getInstance().setSkin(path)
            }
        }
        setChanged()
        notifyObservers()
    }

}